
<template>
  <div class="cart-container">
    <h2 style="text-align: left;margin-left: 20px;">我的购物车</h2>
    <div v-if="cartItems.length > 0" class="cart-items">
      <div v-for="item in cartItems" :key="item.id" class="cart-item">
        <div class="item-details">
          <span class="item-id">{{ item.itemId }}</span>

          <span class="item-name">{{ item.name }}</span>

          <span class="item-count"> - {{ item.amount }} 件</span>
          <span class="item-price"> - ￥{{ item.price }}</span>
        </div>
        <div class="item-controls">
          <button @click="updateAmount(item.id, item.amount - 1)" :disabled="item.amount <= 1" class="control-button">-</button>
          <span class="item-count-display">{{ item.amount }}</span>
          <button @click="updateAmount(item.id, item.amount + 1)" class="control-button">+</button>
          <button @click="removeFromCart(item.id)" class="delete-button">删除</button>
        </div>
      </div>
    </div>
    <div v-else class="empty-cart">
      购物车为空
    </div>
    <div v-if="error" class="error">{{ error }}</div> <!-- 显示错误提示 -->

    <div v-if="isCheckingOut" class="checking-out">正在结算...</div>
    <div v-if="checkoutSuccess" class="checkout-success">结算成功！</div>
    <div v-if="checkoutError" class="checkout-error">结算失败，请稍后再试。</div>

    <div class="total">
      <span>总价:</span> ￥{{total}}
    </div>
    <button @click="checkout" :disabled="!cartItems.length || isCheckingOut" class="checkout-button">结算</button>
  </div>

</template>
<script>
import axios from 'axios';

export default {
  data() {
    return {
      userId: 1, // 假设用户ID为1，这里需要根据实际用户信息来设置
      cartItems: [],
      total: 0.0,
      error:null,//错误状态
      isCheckingOut: false, // 结算状态
      checkoutSuccess: false, // 结算成功状态
      checkoutError: false, // 结算失败状态
    };
  },
  created() {
     //this.fetchCart();
    this.fetchProducts();
  },
  methods: {
    fetchProducts() {
      axios.get('/cart/list')
          .then(response => {
            this.cartItems = response.data.map(item => ({
              ...item,
            }));
            this.calculateTotalPrice();
          })
          .catch(error => {
            console.error('There was an error fetching the items:', error);
          });
    },
    async updateAmount(id, amount) {
      try {
        const cartItem = { id, amount, price: this.getPriceById(id) };
        await axios.put('/cart/update', cartItem);
        this.fetchProducts();
      } catch (error) {
        this.error = "更新购物车失败，请稍后再试"; // 设置错误提示
        console.error("Error updating cart item:", error);
      }
    },
    async removeFromCart(id) {
      try {
        await axios.delete(`/cart/delete/${id}`);
        this.fetchProducts();
      } catch (error) {

        this.error = "删除购物车商品失败，请稍后再试";
        console.error("Error removing cart item:", error);
      }
    },
    getPriceById(id) {
      const item = this.cartItems.find(item => item.id === id);
      return item ? item.price : 0.0;
    },
    calculateTotalPrice() {
      this.total = this.cartItems.reduce((total, item) => total + item.price * item.amount, 0.0);
    },

    /*结算*/
    async checkout() {
      if (this.isCheckingOut || !this.cartItems.length) return;

      this.isCheckingOut = true;
      this.checkoutSuccess = false;
      this.checkoutError = false;

      try {
         await axios.post('/orders/create', {
          // userId: this.userId,
          cartItems: this.cartItems.map(item => ({
            id: item.id,
            amount: item.amount,
            price: item.price,
          })),
        });

        // 假设服务器返回订单创建成功的信息
        this.isCheckingOut = false;
        this.checkoutSuccess = true;
        this.cartItems = []; // 清空购物车
        this.total = 0.0;
        this.error = null;

        // 可以选择重定向到订单详情页或其他页面
        // this.$router.push('/order-details/' + response.data.orderId);

      } catch (error) {
        this.isCheckingOut = false;
        this.checkoutError = true;
        console.error("Error checking out:", error);
      }
    }
  }
};
</script>
<style scoped>

.cart-container {
  width: 80%;
  max-width: 1200px;
  margin: 10px auto;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 15px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  background-color: #fff;
}

h2 {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.cart-items {
  margin-bottom: 30px;
}

.cart-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.cart-item:last-child {
  border-bottom: none;
}

.item-details {
  display: flex;
  align-items: center;
}

.item-id {
  font-size: 1.1em;
  color: #555;
}

.item-count, .item-price {
  margin-left: 10px;
  color: #777;
}

.item-controls {
  display: flex;
  align-items: center;
}

.control-button, .delete-button {
  min-width: 30px;
  height: 30px;
  border: 1px solid #ddd;
  border-radius: 5px;
  background-color: #f9f9f9;
  color: #333;
  cursor: pointer;
  transition: background-color 0.3s, color 0.3s;
}

.control-button:hover, .delete-button:hover {
  background-color: #eee;
}

.control-button:disabled {
  background-color: #f0f0f0;
  color: #aaa;
  cursor: not-allowed;
}

.delete-button {
  margin-left: 10px;
  background-color: #f44336;
  color: #fff;
  border: none;
}

.delete-button:hover {
  background-color: #e53935;
}

.empty-cart {
  text-align: center;
  color: #999;
  padding: 20px;
}

.total {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 10px;
  font-size: 1.2em;
  font-weight: bold;
  color: #333;
}

.total span {
  margin-right: 10px;
}

.checking-out, .checkout-success, .checkout-error {
  text-align: center;
  padding: 20px;
  margin-top: 20px;
  border-radius: 5px;
}

.checking-out {
  background-color: #ffeb3b;
  color: #000;
}

.checkout-success {
  background-color: #4caf50;
  color: #fff;
}

.checkout-error {
  background-color: #f44336;
  color: #fff;
}

.checkout-button {
  display: block;
  width: 100%;
  max-width: 200px;
  margin: 0 auto;
  padding: 10px;
  border: none;
  border-radius: 5px;
  background-color: #2196f3;
  color: #fff;
  font-size: 1.1em;
  cursor: pointer;
  transition: background-color 0.3s;
}

.checkout-button:hover {
  background-color: #1976d2;
}

.checkout-button:disabled {
  background-color: #bbdefb;
  color: #666;
  cursor: not-allowed;
}
</style>
